package com.ks.core.framework.cpsupload.demos.orderpayinvoice.orderhandler;

import com.ks.core.framework.cpsupload.demos.orderpayinvoice.constant.PaymentType;
import com.ks.core.framework.cpsupload.demos.orderpayinvoice.paystrategy.PaymentStrategy;
import com.ks.core.framework.cpsupload.demos.orderpayinvoice.paystrategy.PaymentStrategyFactory;

import java.math.BigDecimal;

// 退款服务
class RefundService {
    public boolean refund(Order order, PaymentType type, BigDecimal amount) {
        // 获取原始支付记录
        PaymentRecord payment = findOriginalPayment(order, type);
        if (payment == null) {
            return false;
        }
        
        // 检查可退款金额
        BigDecimal refundable = getRefundableAmount(order, type);
        if (amount.compareTo(refundable) > 0) {
            return false;
        }
        
        // 执行退款
        PaymentStrategy strategy = PaymentStrategyFactory.getStrategy(type);
        boolean success = strategy.refund(order.getOrderId(), amount, payment.getTransactionId());
        
        if (success) {
            // 添加退款记录
            order.addRefundRecord(type, amount, generateRefundTransactionId());
        }
        
        return success;
    }
    
    public boolean fullRefund(Order order) {
        for (PaymentRecord payment : order.getPaymentRecords()) {
            BigDecimal refundable = getRefundableAmountForPayment(payment);
            if (refundable.compareTo(BigDecimal.ZERO) > 0) {
                refund(order, payment.getPaymentType(), refundable);
            }
        }
        return true;
    }
    
    // 其他辅助方法...
}